﻿#region copyright
//Copyright 2013 Ramon Ordiales Plaza
//
//This file is part of TrayFastMsg.
//
//    TrayFastMsg is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    TrayFastMsg is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with FastMessage.  If not, see <http://www.gnu.org/licenses/>.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Reflection;
using System.Drawing;
using System.Threading;

namespace TrayFastMsg
{
    public class CustomApplicationContext : ApplicationContext
    {
       
        
        private readonly MsgManager msgManager;

        /// <summary>
        /// This class should be created and passed into Application.Run( ... )
        /// </summary>
        public CustomApplicationContext()
        {
            InitializeContext();
            msgManager = new MsgManager(notifyIcon);
        }

        
        # region the child forms

        private Form1 detailsForm;
        
       
        private void ShowForm()
        {
            if (detailsForm == null)
            {
                detailsForm = new Form1 { MsgManager = msgManager };
                detailsForm.Closed += detailsForm_Closed; // avoid reshowing a disposed form
                var r = Screen.PrimaryScreen.WorkingArea;
                var p = new Point(r.Right - detailsForm.Width, r.Bottom - detailsForm.Height);
                detailsForm.Location = p;
                msgManager.NewMessages += detailsForm.OnNewMessage;
            }
            detailsForm.AjListado();
            detailsForm.Show();
            detailsForm.BringToFront();
            detailsForm.Activate();
            
        }

        private void notifyIcon_DoubleClick(object sender, EventArgs e) { ShowForm(); }

        private void notifyIcon_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
                mi.Invoke(notifyIcon, null);
            }
        }

        // null out the forms so we know to create a new one.
        private void detailsForm_Closed(object sender, EventArgs e) {
            if ((detailsForm!=null)&&(msgManager != null)) msgManager.NewMessages -= detailsForm.OnNewMessage;
            detailsForm = null; 

        }
        
        # endregion the child forms

        # region generic code framework

        private System.ComponentModel.IContainer components;	// a list of components to dispose when the context is disposed
        private NotifyIcon notifyIcon;				            // the icon that sits in the system tray

        
        private void InitializeContext()
        {
            components = new System.ComponentModel.Container();
            
            notifyIcon = new NotifyIcon(components)
            {
                Icon=TrayFastMsg.Properties.Resources.alertgrayico,
                Visible = true
            };
            
            //notifyIcon.ContextMenuStrip.Opening += ContextMenuStrip_Opening;
            notifyIcon.DoubleClick += notifyIcon_DoubleClick;
            notifyIcon.MouseUp += notifyIcon_MouseUp;
            notifyIcon.Click += notifyIcon_Click;
        }
        
        

        void notifyIcon_Click(object sender, EventArgs e)
        {
            ShowForm();
        }

        /// <summary>
        /// When the application context is disposed, dispose things like the notify icon.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null) { components.Dispose(); }
        }

        /// <summary>
        /// When the exit menu item is clicked, make a call to terminate the ApplicationContext.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitItem_Click(object sender, EventArgs e)
        {
            ExitThread();
        }

        /// <summary>
        /// If we are presently showing a form, clean it up.
        /// </summary>
        protected override void ExitThreadCore()
        {
            // before we exit, let forms clean themselves up.
            
            if (detailsForm != null) { detailsForm.Close(); }

            notifyIcon.Visible = false; // should remove lingering tray icon
            base.ExitThreadCore();
        }

        # endregion generic code framework

    }
}
